import 'dart:io';

import 'package:flutter/material.dart';

import 'package:flutter_note/note/widgets.dart';
import 'package:flutter_note/note/base.dart';
import 'package:flutter_note/note/bean.dart';
import 'package:flutter_note/note/const.dart';
import 'package:flutter_note/note/manager.dart';
import 'package:flutter_note/note/utils.dart';

class AddBookPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _AddBookPageState();
  }
}

class _AddBookPageState extends BaseState<AddBookPage> {
  TextEditingController _titleController = TextEditingController();
  TextEditingController _msgController = TextEditingController();
  File _image;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: scaffoldkey,
      backgroundColor: color.bg_page,
      appBar: AppBar(
        title: Text('新建日记本'),
        elevation: dim.x2,
        actions: <Widget>[
          GestureDetector(
            onTap: () {
              _createBook();
            },
            child: Container(
                color: Colors.transparent,
                width: dim.x60,
                child: Icon(Icons.check)),
          )
        ],
      ),
      body: ListView(
        controller: ScrollController(keepScrollOffset: false),
        children: <Widget>[
          Space(
            Const.SPACE_TOP,
            size: dim.x20,
          ),
          _bookHead(),
          Space(
            Const.SPACE_TOP,
            size: dim.x20,
          ),
          lineHorizontal(dim.x1),
          _titleTextField(),
          lineHorizontal(dim.x1),
          Space(Const.SPACE_TOP),
          lineHorizontal(dim.x1),
          _msgTextField(),
          lineHorizontal(dim.x1),
          Space(Const.SPACE_TOP),
          _descMessage(),
        ],
      ),
    );
  }

  Widget _descMessage() {
    return Container(
      padding: EdgeInsets.only(left: dim.x15, right: dim.x15),
      child: Text(
        "写下你的日记,记录美好生活",
        style: TextStyle(color: Colors.blueGrey, fontSize: dim.t14),
      ),
    );
  }

  Widget _titleTextField() {
    return Container(
      padding: EdgeInsets.only(left: dim.x15, right: dim.x15),
      color: color.white,
      child: TextField(
        maxLines: 1,
        controller: _titleController,
        keyboardType: TextInputType.text,
        style: TextStyle(fontSize: dim.t16, color: color.txt3),
        decoration: InputDecoration(
            border: InputBorder.none,
            hintText: '主题',
            hintStyle: TextStyle(fontSize: dim.t16, color: color.txt9)),
      ),
    );
  }

  Widget _msgTextField() {
    return Container(
      padding: EdgeInsets.only(left: dim.x15, right: dim.x15),
      color: color.white,
      child: TextField(
        maxLines: 5,
        controller: _msgController,
        keyboardType: TextInputType.text,
        style: TextStyle(fontSize: dim.t16, color: color.txt3),
        decoration: InputDecoration(
            border: InputBorder.none,
            hintText: '请输入日记本描述',
            hintStyle: TextStyle(fontSize: dim.t16, color: color.txt9)),
      ),
    );
  }

  Widget _bookHead() {
    return GestureDetector(
      onTap: () {
        _pickAndUpload();
      },
      child: _headImage(),
    );
  }

  Widget _headImage() {
    var size = dim.x80;
    if (_image != null) {
      return Center(
        child: ClipOval(
          child: Image.file(_image, width: size, height: size),
        ),
      );
    } else {
      return Center(
        child: ClipImageView(null, size, size, Const.IMG_SIZE_NOTE),
      );
    }
  }

  //选择图片,并且上传
  _pickAndUpload() async {
    File image = await ImageUtils.pickImage(true); //上传头像,需要剪裁
    if (image == null) {
      showMessage('选择图片失败');
      return;
    }
    Reply reply = await UploadFileManager.getInstance().uploadFile(image);
    setState(() {
      if (reply.code == Const.SUCCESS) {
        _image = image; //上传成功就更新图片
      } else {
        showMessage('上传图片失败');
      }
    });
  }

  //发送创建笔记本
  _createBook() async {
    if (EmptyUtils.isEmpty(_titleController.text)) {
      showMessage('标题不能为空');
      return;
    }
    show();
    String head = ''; //默认头像
    if (_image != null) {
      head = _image.path.substring(_image.path.lastIndexOf('/') + 1); //头像的名字
    }
    Reply reply = await BookManager.getInstance()
        .createBook(_titleController.text, _msgController.text, head);
    setState(() {
      dismiss();
      if (reply != null) {
        if (reply.code == Const.SUCCESS) {
          Navigator.of(context).pop(reply);
        } else {
          showMessage('新建日记本失败');
        }
      } else {
        showMessage('请求异常');
      }
    });
  }
}
